package com.ssh.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ssh.dataobject.Page;
import com.ssh.dataobject.PageModel;
import com.ssh.dataobject.JqGridSearchDetailTo;
import com.ssh.dataobject.JqGridSearchTo;

import com.ssh.model.TableGoods;
//import com.ssh.model.PeopleImage;
//import com.ssh.model.People;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.annotations.JSON;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ssh.service.IGoodsService;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/****
 * 用户模块action层
 * ******/
public class GoodsAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 557281694763970986L;
	// private static final long serialVersionUID = 3096628984388465807L;
	private TableGoods g;
	// private List<Users> userList;
	private List<TableGoods> tablegoodsList;
	private IGoodsService goodsService;
	private String checkCodeStr;

	private String id;
	private String code;
	private String name;
	private String peoplecode;
	private String details;
	private String relatives;
	private String rowid;
	private String epc;

	/********************************************************************************************/
	/**
	 * 以下属性用于序列化成json格式的数据。名称不能改。如果要改，客户端页面对应的地方也要改； 或通过@JSON来指定序列化的名字
	 */
	private String groupOp; // 多字段查询时分组类型，主要是AND或者OR
	private List rules; // 多字段查询时候，查询条件的集合

	private int curPageNo; // 当前第几页
	private int pageSize; // 每页显示多少条数据
	private String order; // 排序字段
	private String orderBy; // 排序类型 ASC或者DESC
	private boolean _search; // 是否是查询 true 或者 false
	private String nd; // 暂时不清楚啥用的
	private boolean search;
	private String searchField; // 单字段查询的时候，查询字段名称
	private String searchString; // 单字段查询的时候，查询字段的值
	private String searchOper; // 单字段查询的时候，查询的操作
	private String filters;
	PageModel pageModel = new PageModel();
	private int total;
	private String ajaxResult;

	public PageModel getPageModel() {
		return pageModel;
	}

	public void setPageModel(PageModel pageModel) {
		this.pageModel = pageModel;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public String getAjaxResult() {
		return ajaxResult;
	}

	public void setAjaxResult(String ajaxResult) {
		this.ajaxResult = ajaxResult;
	}

	/**** 操作类型 *****/
	private String oper;

	/*** 分页数 *****/
	private Page page;
	/**
	 * 总页数
	 */
	private int totalPages;

	/**
	 * 显示第几页
	 */
	private int curPage;
	/**
	 * 总记录数
	 */
	private int totalRecords;
	/**
	 * 保存实际的数据
	 */
	private List<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();

	private File btn_file;// 特别注意，名字要与jsp页面<input type="file"
							// name="btn_file"/>这个name一致，否则得不到值
	private String btn_fileFileName;// 文件名
	private String btn_fileContentType;
	private String imPath;
	private String message = "上传成功";

	@JSON(serialize = false)
	public File getBtn_file() {
		return btn_file;
	}

	public void setBtn_file(File btnFile) {
		btn_file = btnFile;
	}

	@JSON(serialize = false)
	public String getBtn_fileFileName() {
		return btn_fileFileName;
	}

	public void setBtn_fileFileName(String btnFileFileName) {
		btn_fileFileName = btnFileFileName;
	}

	@JSON(serialize = false)
	public String getBtn_fileContentType() {
		return btn_fileContentType;
	}

	public void setBtn_fileContentType(String btnFileContentType) {
		btn_fileContentType = btnFileContentType;
	}

	public String getImPath() {
		return imPath;
	}

	public void setImPath(String imPath) {
		this.imPath = imPath;
	}

	/***************************** 编辑添加删除用户信息操作跳转 ***************************************/
	public void submitGoods() throws Exception {

		System.out.println("GoodsAction.submitGoods() oper:" + oper);
		String result = null;

		System.out.println(name);
		System.out.println("****************");
		if ("add".equalsIgnoreCase(oper)) {
			result = this.addGoods();
			System.out.println("AAAA");

		} else if ("del".equalsIgnoreCase(oper)) {
			result = this.delGoods();

		} else if ("edit".equalsIgnoreCase(oper)) {
			result = this.updateGoods();

		}
		System.out.println(result);

	}

	/**** 删除用户功能 ***/
	public String delGoods() throws Exception {

		TableGoods goods;

		System.out.println("删除物品");
		boolean flag = false;
		try {
			goods = goodsService.findById(Integer.parseInt(id));
			flag = goodsService.delGoods(goods);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (flag) {
			JSONObject json = new JSONObject();
			try {
				json.put("status", "success");

			} catch (JSONException e) {
				e.printStackTrace();
			}

			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}

			out.println(json);
			System.out.println("json数据：" + json);
			out.flush();
			out.close();
			return SUCCESS;
		} else {

			return ERROR;
		}
	}

	/******** 获得所有用户信息 **********/
	public void getAllGoods() {

		// int totalSize=60;//假设数据库中总共有60条数据
		// int totalSize=all.size();//获取数据库中的所有用户的数据

		System.out.println("----getAllGoods----");
		System.out.println(this.filters);// 查询用户时的参数filters
		StringBuffer hql = null;
		boolean isFirst = true;
		if (!(filters == null || filters.equals(""))) {// 解析json数据filters
			hql = new StringBuffer();
			JSONObject jsonObject = new JSONObject(this.filters);
			String groupOp = jsonObject.getString("groupOp");// 解析filters中的groupOp
			System.out.println("--groupOp-- :" + groupOp);
			JSONArray jsonArray = jsonObject.getJSONArray("rules");// 解析filters中的rules
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObjectTemp = jsonArray.getJSONObject(i);
				String field = jsonObjectTemp.getString("field");
				String data = jsonObjectTemp.getString("data");
				if (isFirst) {
					isFirst = false;
				} else {
					hql.append(" " + groupOp + " ");
				}
				hql.append(" model." + field + " like '%" + data + "%'");

			}
			System.out.println("---hql-:" + hql);
		}
		int pageSize = page.getPageSize();
		int offset = (page.getCurPageNo() - 1) * pageSize;
		int total = 0;// 获取数据库中的所有用户的数据
		// System.out.println("count="+count);
		// int total=count;//获取数据库中的所有用户的数据

		List<TableGoods> list = new ArrayList<TableGoods>();
		List<TableGoods> all = null;
		if (hql != null) {
			all = goodsService.findGoodsListByHQL(hql.toString());
			total = all.size();
			int limit = offset + pageSize >= total ? total : offset + pageSize;
			for (int i = offset; i < limit; i++) {
				TableGoods goods = new TableGoods();
				goods = all.get(i);
				goods.setId(goods.getId());
				goods.setName(goods.getName());
				goods.setCode(goods.getCode());
				goods.setDetails(goods.getDetails());
				goods.setPeoplecode(goods.getPeoplecode());
				goods.setEpc(goods.getEpc());

				goods.setRelatives(goods.getRelatives());
				list.add(goods);
			}
		} else {
			total = goodsService.countGoods();
			// all =usersService.findAll();

			all = goodsService.findAllPage(offset, pageSize);// 分页获取数据
			for (int i = 0; i < all.size(); i++) {
				TableGoods goods = new TableGoods();
				goods = all.get(i);
				goods.setId(goods.getId());
				goods.setName(goods.getName());
				goods.setCode(goods.getCode());
				goods.setDetails(goods.getDetails());
				goods.setPeoplecode(goods.getPeoplecode());
				goods.setEpc(goods.getEpc());

				goods.setRelatives(goods.getRelatives());
				list.add(goods);

			}
		}

		if (all == null) {
			System.out.println("all==null");
		} else {
			System.out.println("all.size()" + all.size());
		}

		Map<Object, Object> info = new HashMap<Object, Object>();
		info.put("dataRows", list);
		info.put("curPage", page.getCurPageNo());
		info.put("totalPages", total % pageSize == 0 ? total / pageSize : total
				/ pageSize + 1);//
		info.put("totalRecords", total);// 总共有totalSize条数据
		String json = new Gson().toJson(info);

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}

		out.println(json);
		System.out.println("json数据：" + json);

		out.flush();
		out.close();

	}

	/****
	 * 模拟插入数据20条
	 * 
	 * ****/
	/*
	 * public void insertData2(){ int i=0;
	 * 
	 * TableGoods goods=new TableGoods(); goods.setId(22); goods.setCode("HHH");
	 * goods.setName("zhang"+i); goods.setInstrution("kongzhi");
	 * goods.setPerson("wudi"+i); goods.setPreuser("1"+i);
	 * 
	 * try{ goodsService.updateGoods(goods); }catch(Exception e){
	 * e.printStackTrace(); }
	 * 
	 * System.out.println("*******************");
	 * 
	 * JSONObject json=new JSONObject(); try{ json.put("ddd", 1111);
	 * json.put("time",new Date()); }catch(JSONException e){
	 * e.printStackTrace(); }
	 * 
	 * /////// HttpServletResponse response =
	 * ServletActionContext.getResponse(); response.setContentType("text/json");
	 * response.setCharacterEncoding("UTF-8"); PrintWriter out =null; try{ out =
	 * response.getWriter(); }catch(IOException e){ e.printStackTrace(); }
	 * 
	 * out.println(json); System.out.println("json数据：" + json); out.flush();
	 * out.close(); }
	 */
	/**** 添加用户 ******/
	public String addGoods() {
		TableGoods goods = new TableGoods();
		// user.setId(id);
		// people.setId(id);
		System.out.println("BBBB");
		goods.setCode(code);
		// goods.setId(Integer.parseInt(id));
		goods.setName(name);
		goods.setDetails(details);
		goods.setEpc(epc);
		goods.setPeoplecode(peoplecode);

		goods.setRelatives(relatives);
		// people.setPicture(picture);

		boolean flag = false;
		try {

			if (goodsService.findByName(goods.getName()) != null) {
				System.out.println("该goods已存在");
				flag = false;
			} else {
				System.out.println("QQQ");
				flag = goodsService.addGoods(goods);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		ActionContext context = ActionContext.getContext();
		context.getSession().put("addPeople", flag);

		System.out.println("new goods" + name);
		if (flag) {
			JSONObject json = new JSONObject();
			try {
				json.put("status", "success");

			} catch (JSONException e) {
				e.printStackTrace();
			}

			// /////
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}

			out.println(json);
			System.out.println("json数据：" + json);
			out.flush();
			out.close();
			return SUCCESS;
		} else {

			return ERROR;
		}

	}

	/******** 更新用户 ***********/
	public String updateGoods() throws Exception {

		TableGoods goods = new TableGoods();
		goods.setCode(code);
		goods.setId(Integer.parseInt(id));
		goods.setName(name);
		goods.setDetails(details);
		goods.setEpc(epc);
		goods.setPeoplecode(peoplecode);

		goods.setRelatives(relatives);
		// people.setPicture(picture);

		System.out.println("更新" + name);
		boolean flag = false;
		try {
			// if(usersService.findByName(user.getUsername())!=null){
			// System.out.println("用户名已存在");
			// flag=false;
			// }else{
			flag = goodsService.updateGoods(goods);
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
		ActionContext context = ActionContext.getContext();
		context.getSession().put("editGoods", flag);
		if (flag) {
			JSONObject json = new JSONObject();
			try {
				json.put("status", "success");

			} catch (JSONException e) {
				e.printStackTrace();
			}

			// /////
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}

			out.println(json);
			System.out.println("json数据：" + json);
			out.flush();
			out.close();
			return SUCCESS;
		} else {

			return ERROR;
		}

	}

	public void checkName() throws Exception {

		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		System.out.println(g.getName());
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject jsonResult = new JSONObject();

		try {
			jsonResult.put("status", "y");
			jsonResult.put("info", "用户名合法");

		} catch (Exception e) {

			e.printStackTrace();

		}

		out.print(jsonResult);
		out.flush();
		out.close();
	}

	/***************** 增加一个ajax的实现个人资料中的数据与后台异步交互 ********************************/
	public void exampleAjax2() throws IOException, JSONException {
		HttpServletRequest request = ServletActionContext.getRequest();
		String name = request.getParameter("name");
		String code = request.getParameter("code");
		String goodsid = request.getParameter("goodsid");
		String instrution = request.getParameter("instrution");
		String person = request.getParameter("person");
		String preuser = request.getParameter("preuser");

		TableGoods goods = new TableGoods();
		goods.setCode(code);
		goods.setId(Integer.parseInt(id));
		goods.setName(name);
		goods.setDetails(details);
		goods.setEpc(epc);
		goods.setPeoplecode(peoplecode);

		goods.setRelatives(relatives);
		// people.setPicture(picture);

		boolean flag = false;
		try {
			flag = goodsService.updateGoods(goods);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (flag) {
			JSONObject json = new JSONObject();
			try {
				json.put("status", "success");
				json.put("name", goods.getName());
				json.put("code", goods.getCode());
				json.put("epc", goods.getEpc());
				json.put("relatives", goods.getRelatives());
				json.put("id", goods.getId());

				json.put("peoplecode", goods.getPeoplecode());
				json.put("details", goods.getDetails());
				// json.put("picture", Goods.getPicture());
				// json.put("picture", people.getPicture());
			} catch (JSONException e) {
				e.printStackTrace();
			}

			// /////
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/json");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}

			out.println(json);
			System.out.println("json数据：" + json);
			out.flush();
			out.close();
			// return SUCCESS;
		}
	}

	public TableGoods getG() {
		return g;
	}

	public void setG(TableGoods g) {
		this.g = g;
	}

	public List<TableGoods> getTablegoodsList() {
		return tablegoodsList;
	}

	public void setTablegoodsList(List<TableGoods> tablegoodsList) {
		this.tablegoodsList = tablegoodsList;
	}

	//

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public IGoodsService getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(IGoodsService goodsService) {
		this.goodsService = goodsService;
	}

	public String getCheckCodeStr() {
		return checkCodeStr;
	}

	public void setCheckCodeStr(String checkCodeStr) {
		this.checkCodeStr = checkCodeStr;
	}

	/*
	 * 以下getter方法必须实现，struts2-json插件会将这些getter方法序列化，以便输出json对象。
	 * 这些getter方法只需返回相应的属性即可。如getCurPage应该返回curPage （curPage在JsonBaseAction中有定义）
	 */
	public String getOper() {
		return oper;
	}

	public void setOper(String oper) {
		this.oper = oper;
	}

	public int getTotalPages() {
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public int getTotalRecords() {
		return totalRecords;
	}

	public void setTotalRecords(int totalRecords) {
		this.totalRecords = totalRecords;
	}

	public List<Map<String, Object>> getDataRows() {
		return dataRows;
	}

	public void setDataRows(List<Map<String, Object>> dataRows) {
		this.dataRows = dataRows;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	// public String getPicture() {
	// return picture;
	// }

	// public void setPicture(String picture) {
	// this.picture = picture;
	// }

	public Page getPage() {
		return page;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPeoplecode() {
		return peoplecode;
	}

	public void setPeoplecode(String peoplecode) {
		this.peoplecode = peoplecode;
	}

	public String getDetails() {
		return details;
	}

	public void setDetails(String details) {
		this.details = details;
	}

	public String getRelatives() {
		return relatives;
	}

	public void setRelatives(String relatives) {
		this.relatives = relatives;
	}

	public String getRowid() {
		return rowid;
	}

	public void setRowid(String rowid) {
		this.rowid = rowid;
	}

	public String getEpc() {
		return epc;
	}

	public void setEpc(String epc) {
		this.epc = epc;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public void setSearchField(String searchField) {
		this.searchField = searchField;
	}

	public String getSearchField() {
		return searchField;
	}

	public void setSearchString(String searchString) {
		this.searchString = searchString;
	}

	public String getSearchString() {
		return searchString;
	}

	public void setSearchOper(String searchOper) {
		this.searchOper = searchOper;
	}

	public String getSearchOper() {
		return searchOper;
	}

	public void setSearch(boolean search) {
		this.search = search;
	}

	public boolean isSearch() {
		return search;
	}

	public String getFilters() {
		return filters;
	}

	public void setFilters(String filters) {
		this.filters = filters;
	}

	public String getGroupOp() {
		return groupOp;
	}

	public void setGroupOp(String groupOp) {
		this.groupOp = groupOp;
	}

	public List getRules() {
		return rules;
	}

	public void setRules(List rules) {
		this.rules = rules;
	}

	public int getCurPageNo() {
		return curPageNo;
	}

	public void setCurPageNo(int curPageNo) {
		this.curPageNo = curPageNo;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getOrderBy() {
		return orderBy;
	}

	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}

	public boolean is_search() {
		return _search;
	}

	public void set_search(boolean search) {
		_search = search;
	}

	public String getNd() {
		return nd;
	}

	public void setNd(String nd) {
		this.nd = nd;
	}
}
